$(function(){

    var allPage,page,searchKey,orderId;

    // 页面初始化
    page = getWaitGoodsList( 1,10,2,'' );
    getPage(page);

    // 页面初始化...已完成订单列表...
    function getWaitGoodsList( page,size,type,searchKey )
    {
        $.ajax({
            async:false,
            cache:false,
            type:'post',
            headers: {"Accept-CMS-Token":token},
            url:findall,
            data:{
                page:page,
                size:size,
                type:type,
                querystr:searchKey
            },
            dataType:'json',
            success:successFn,
            error:function(){
                console.log('查询订单接口请求失败')
            },
        });
        return allPage;
    };

    //已完成订单列表...请求成功之后....要执行此函数....后台数据还没有就绪...没办法进行..
    function successFn(data)
    {
        if( data.resultCode == 200 )
        {
            allPage = data.count;
            var value = data.value;
            // 清空表格
            clearTable();
            for( var i=0;i<value.length;i++ )
            {
                $('.wait_goods').append('<tr orderId="'+value[i].id+'"></tr>');//属性

                $('.wait_goods tr').eq(i+1).append('<td>'+(i+1)+'</td>');

                $('.wait_goods tr').eq(i+1).append('<td>'+changeNull(value[i].orderNum)+'</td>');//订单编号

                $('.wait_goods tr').eq(i+1).append('<td>'+changeNull(value[i].userId)+'</td>');

                $('.wait_goods tr').eq(i+1).append('<td>'+changeNull(value[i].userNickName)+'</td>');

                $('.wait_goods tr').eq(i+1).append('<td>'+getMoth(value[i].createTime)+'</td>');//下单时间

                $('.wait_goods tr').eq(i+1).append('<td>'+getMoth(value[i].payTime)+'</td>');//支付时间

                $('.wait_goods tr').eq(i+1).append('<td>'+changeOrderStatus(value[i].orderStatus)+'</td>');//订单状态

                $('.wait_goods tr').eq(i+1).append('<td>'+changeNull(value[i].receiveName)+'</td>');//收货人

                $('.wait_goods tr').eq(i+1).append('<td>'+changeNull(value[i].receivePhone)+'</td>');//联系电话

                $('.wait_goods tr').eq(i+1).append('<td>'+setShippingAddress(value[i].receiveAddress)+'</td>');//收货地址

                $('.wait_goods tr').eq(i+1).append('<td>'+changeNull(value[i].expressSendTime)+'</td>');//发货时间

                $('.wait_goods tr').eq(i+1).append('<td>'+changeNull(value[i].expressSendName)+'</td>');//发货人

                $('.wait_goods tr').eq(i+1).append('<td>'+changeNull(value[i].expressCompanyName)+'</td>');//快递公司

                $('.wait_goods tr').eq(i+1).append('<td>'+changeNull(value[i].expressNum)+'</td>');//物流单号

                if( value[i].orderStatus == 2 )
                {
                    if( value[i].isRefound == 0 )
                    {//没有申请退款
                        $('.wait_goods tr').eq(i+1).append('<td>'+'<a class="ed delivery_goods" href="#">发货</a><a class="look_waitGoods" href="#">查看</a>'+'</td>')
                    }
                    else if( value[i].isRefound == 1 )
                    {//有申请退款...发货的按钮是处于禁用状态,,,,灰度显示....
                        $('.wait_goods tr').eq(i+1).append('<td>'+'<a class="ed dis" href="#">发货</a><a class="look_waitGoods" href="#">查看</a>'+'</td>')
                    };
                    // return '待发货';
                };
            };
            // console.log(data);
        }
        else if( data.resultCode == 500 )
        {//这种状态下...要搜索的东西是空的...
            clearTable();
            $('.wait_goods').append('<tr><td></td><td></td><td></td><td></td><td>您搜索的内容不存在</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>');
            hintUser();
            allPage = 1;
        }
        else if(data.resultCode == 515)
        {
            reLogin()
        };
        console.log('查询订单接口请求成功!!!!')
    };

    //清空表格当中的数据,并且追加表头
    function clearTable()
    {
        $('.wait_goods').html('');
        $('.wait_goods').append('<tr></tr>');
        $('.wait_goods tr').eq(0).append('<th>序号</th><th>订单编号</th><th>买家ID</th><th>买家昵称</th><th>下单时间</th><th>支付时间</th><th>订单状态</th><th>收货人</th><th>联系电话</th><th>收货地址</th><th>发货时间</th><th>发货人</th><th>快递公司</th><th>物流单号</th><th>操作</th>');
    };

    // 分页插件封装   为分页插件传递数据
    function getPage(allPage)
    {
        $('.M-box2').pagination({
            pageCount:allPage,
            jump:true,
            coping:true,
            homePage:'首页',
            endPage:'末页',
            prevContent:'上页',
            nextContent:'下页',
            callback:function (api){//当点击页面当中的时候,会出发这个callback函数;;;;
                page = api.getCurrent()+"";//得到的是要跳转到的那一页的页码;
                searchKey = $('input[name = wait_goods_cont]').val().sTrim();
                getWaitGoodsList(  page,10,5,searchKey )
            }
        });
    };

    // 页面的搜索功能
    $('.search_wait_goods').click(function(){

        searchKey = $('input[name = wait_goods_cont]').val().sTrim();
        page = getWaitGoodsList(  1,10,2,searchKey );
        getPage(page);

        // 导出订单
        exportOrder(2,searchKey);
    });

    //当输入文本框中时,,,按下enter键,,,发起搜索,,,
    $(document).keydown(function(event){
        var ev = ev || event;

        if( ev.keyCode == 13 )
        {
            searchKey = $('input[name = wait_goods_cont]').val().sTrim();
            page = getWaitGoodsList(  1,10,2,searchKey );
            getPage(page);

            // 导出订单
            exportOrder(2,searchKey);
        };

    });

    // 点击查看...跳转到查看的页面...
    $(document).on('click','.look_waitGoods',function(){

        var orderId = $(this).parent('td').parent('tr').attr('orderId');
        window.location.href = look_waitGoods + '?orderId=' + orderId ;

    });

    // 从后台获取快递公司....需要用到ajax请求接口...
    function getExpressCompany( type )
    {
        $.ajax({
            type:'post',
            headers: {"Accept-CMS-Token":token},
            url:finddictlist,
            dataType:'json',
            data:{
                type:type
            },
            success:function(data){
                if(data.resultCode == 200)
                {
                    var value = data.value;
                    $('.expressCompany').html('');
                    $('.expressCompany').append('<option value="">请选择快递公司</option>');
                    for( var i=0;i<value.length;i++ )
                    {
                        $('.expressCompany').append('<option value="'+value[i].id+'" description="'+value[i].description+'">'+value[i].name+'</option>');
                    };
                }
                else if(data.resultCode == 515)
                {
                    reLogin();
                }
                else
                {
                    console.log('接口出错!非200,非515!')
                };
                // console.log(data)
                console.log('获取标签列表接口....请求成功!!!')
            },
            error:function(){
                console.log('获取标签列表接口....请求失败...')
            },
        });
    };

    //点击列表页中的发货...弹出弹框...在点击发货的时候
    $(document).on('click','.delivery_goods',function(){

        orderId = $(this).parent('td').parent('tr').attr('orderid');
        getExpressCompany(5);
        $('.mask-change').show();
        $('.delivery_tankuang').show();

    });
// console.log(JSON.parse(base.decode(localStorage.getItem( base.encode('userinfo') )) ).id)
    //点击确定发货...跟后台做交互...
    $('.sure_delivery').click(function(){

        var expressNum = $('input[name = expressNum]').val();
        var expressCompanyId  = $('.expressCompany option:selected').val();
        var expressCompanyName = $('.expressCompany option:selected').html();
        var expressCompanyNameSimple = $('.expressCompany option:selected').attr('description');

        // 首先要验证必填项输入不能为空...
        if( expressNum == '' || expressCompanyId == '' )
        {
            alert('必填项不能为空!!')
        }
        else
        {
            $.ajax({
                type:'post',
                headers: {"Accept-CMS-Token":token},
                url:sendout,
                dataType:'json',
                data:{
                    userid:JSON.parse(base.decode(localStorage.getItem( base.encode('userinfo') )) ).id,
                    expressSendName:JSON.parse(base.decode(localStorage.getItem( base.encode('userinfo') )) ).name,
                    expressCompanyId:expressCompanyId,
                    expressCompanyName:expressCompanyName,
                    expressCompanyNameSimple:	expressCompanyNameSimple,
                    expressNum:expressNum,
                    orderId:orderId,
                    type:0
                },
                success:function(data){
                    if(data.resultCode == 200)
                    {
                        alert('发货成功!');
                        // 发货成功之后再次请求一下后台...重新刷新一下整个页面
                        page = getWaitGoodsList( 1,10,2,'' );
                        getPage(page);
                        $('.mask-change').hide();
                        $('.delivery_tankuang').hide();
                    }
                    else if(data.resultCode == 515)
                    {
                        reLogin();
                    }
                    else
                    {
                        console.log('接口出错!非200,非515!')
                    };
                    // console.log(data)
                    console.log('获取标签列表接口....请求成功!!!')
                },
                error:function(){
                    console.log('获取标签列表接口....请求失败...')
                },
            });

        };



    });

    //从后台获取所有订单的数据...为导出 表格做准备....导出全部订单...
    function exportOrder(type,searchKey)
    {
        //清空隐藏的表格的内容...并且追加表头...
        clearHideWaitGoodsTable('.wait_table');

        $.ajax({
            async:false,
            type:'post',
            headers: {"Accept-CMS-Token":token},
            url:exportorder,
            data:{
                type:type,
                querystr:searchKey
            },
            dataType:'json',
            success:function(data){
                if(data.resultCode == 200)
                {
                    var list = data.value;
                    var len = list.length;
                    for( var i=0;i<len;i++ )
                    {
                        $('.wait_table tbody').append('<tr orderid="'+list[i].id+'"></tr>');

                        $('.wait_table tbody tr').eq(i).append('<td>'+(i+1)+'</td>');//序号

                        $('.wait_table tbody tr').eq(i).append('<td>'+(list[i].shopOrder.orderNum)+'</td>');//订单编号

                        $('.wait_table tbody tr').eq(i).append('<td>'+list[i].shopCommodityOrder.commodityName+'</td>');//商品名称

                        $('.wait_table tbody tr').eq(i).append('<td>'+changeNull(list[i].shopCommodityOrder.amount)+'</td>');//数量

                        $('.wait_table tbody tr').eq(i).append('<td>'+changeNull(list[i].shopCommodityOrder.colors)+'</td>');//颜色

                        $('.wait_table tbody tr').eq(i).append('<td>'+changeNull(list[i].shopCommodityOrder.sizeName)+'</td>');//尺寸

                        $('.wait_table tbody tr').eq(i).append('<td>'+changeNull(list[i].shopCommodityOrder.modelName)+'</td>');//型号

                        $('.wait_table tbody tr').eq(i).append('<td>'+changeNull(list[i].shopCommodityOrder.prices)+'</td>');//单价

                        $('.wait_table tbody tr').eq(i).append('<td>0</td>');//邮费

                        $('.wait_table tbody tr').eq(i).append('<td>'+changeNull(list[i].shopOrder.totalMoney)+'</td>');//金额

                        $('.wait_table tbody tr').eq(i).append('<td>'+changeOrderStatus(list[i].shopOrder.orderStatus)+'</td>');//订单状态

                        $('.wait_table tbody tr').eq(i).append('<td>'+changeNormalGoods(list[i].shopCommodityOrder.status)+'</td>');//商品状态

                        $('.wait_table tbody tr').eq(i).append('<td>'+changeNull(list[i].shopOrder.userId)+'</td>');//买家ID

                        $('.wait_table tbody tr').eq(i).append('<td>'+changeNull(list[i].shopOrder.userNickName)+'</td>');//买家昵称

                        $('.wait_table tbody tr').eq(i).append('<td>'+getMoth(list[i].shopOrder.createTime)+'</td>');//下单时间

                        $('.wait_table tbody tr').eq(i).append('<td>'+getMoth(list[i].shopOrder.payTime)+'</td>');//支付时间

                        $('.wait_table tbody tr').eq(i).append('<td>'+changeNull(list[i].shopOrder.receiveName)+'</td>');//收货人

                        $('.wait_table tbody tr').eq(i).append('<td>'+changeNull(list[i].shopOrder.receivePhone)+'</td>');//电话

                        $('.wait_table tbody tr').eq(i).append('<td>'+(list[i].shopOrder.receiveAddress)+'</td>');//收货地址

                        $('.wait_table tbody tr').eq(i).append('<td>'+(list[i].shopOrder.message)+'</td>');//买家留言

                    };

                }
                else if( data.resultCode == 500 )
                {//这种情况下没有数据
                    $('.wait_table tbody').append('<tr><td></td><td></td></td><td>没有数据...</td></tr>');
                }
                else if(data.resultCode == 515)
                {
                    reLogin();
                };

                console.log($('.wait_table tbody tr').length);
                console.log('导出订单接口请求成功!!!')
            },
            error:function(){
                console.log('导出订单接口请求失败')
            },
        });

    };
    exportOrder(2,'');

    /*
     正常流程订单列表页在导出表格时....把隐藏的表格清空...然后追加表头..
     */
    function clearHideWaitGoodsTable(Dom)
    {
        $(Dom).html('');
        $(Dom).append('<thead><tr><th>序号</th><th>订单编号</th><th>商品名称</th><th>数量</th><th>颜色</th><th>尺寸</th><th>型号</th><th>单价</th><th>邮费</th><th>金额</th><th>订单状态</th><th>商品状态</th><th>买家ID</th><th>买家昵称</th><th>下单时间</th><th>支付时间</th><th>收货人</th><th>电话</th><th>收货地址</th><th>买家留言</th></tr></thead><tbody></tbody>');

    };
















});
